package cn.calm.maven.copy.plugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
 * 
 * @goal copy
 * @phase package
 */
public class CopyMojo extends AbstractMojo {
	/**
	 * @parameter expression="${target}" default-value="${project.build.directory}"
	 */
	private String target;
	/**
	 * @parameter expression="${source}" default-value="${project.build.directory}/${pom.artifactId}-${pom.version}.jar"
	 */
	private String source;

	public void execute() throws MojoExecutionException, MojoFailureException {

		if (source == null) {
			getLog().info("source is null ");
			return;
		}

		if (target == null) {
			getLog().info("target is null ");
			return;
		}
		File file=new File(source);
		if(!file.isFile()){
			getLog().info("文件"+file+"不存在!");
		}
		FileInputStream fis = null;
		FileOutputStream fos = null;
		File targetFile=new File(target+File.separator+file.getName());
		if(!targetFile.getParentFile().isDirectory()){
			targetFile.getParentFile().mkdirs();
		}
		getLog().info("原文件:" +file.getAbsolutePath());
		try {
			getLog().info("目标文件:" +targetFile.getCanonicalPath());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			fis=new FileInputStream(file);
			fos=new FileOutputStream(targetFile);
			int length;
			byte[] buf=new byte[1024];
			while((length=fis.read(buf))!=-1){
				fos.write(buf, 0, length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if( fis!=null){
				try {
					 fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

}
